<template>
  <div ref="container" class="player" @dblclick="handleFullScreen">
    <!-- <div class="btn-close flex items-center justify-end">
      <CloseOutlined @click="handleDestroyJessibuca" />
    </div> -->
    <div ref="btn-tools" class="btn-box flex items-center">
      <div class="btn-box-left flex items-center justify-between">
        <template v-if="!playing">
          <CaretRightOutlined title="播放" @click="handlePlayVideo" />
        </template>
        <template v-if="playing">
          <PauseOutlined title="暂停" @click="handlePauseVideo" />
        </template>
      </div>
      <div class="btn-box-right flex items-center justify-end">
        <span class="jessibuca-btn">{{ kBps }} kb/s</span>
        <redo-outlined title="重新加载" @click="handlePlayVideo" />
        <template v-if="fullscreen">
          <shrink-outlined title="缩小" @click="handleFullScreen" />
        </template>
        <template v-if="!fullscreen">
          <arrows-alt-outlined title="放大" @click="handleFullScreen" />
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import '@/assets/js/jessibuca/jessibuca.js';
import { watch, ref, defineComponent, getCurrentInstance, nextTick, onUnmounted } from 'vue';
import { CaretRightOutlined, PauseOutlined, ShrinkOutlined, ArrowsAltOutlined, RedoOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { useUserStore } from '/@/store/modules/user';

let jessibucaPlayer = {};

export default defineComponent({
  components: { CaretRightOutlined, PauseOutlined, ShrinkOutlined, ArrowsAltOutlined, RedoOutlined, CloseOutlined },
  props: {
    videoUrl: {
      type: String,
      default: '',
    },
    idx: {
      type: String,
      default: 0,
    },
  },
  emits: ['destroy'],
  setup(props, { emit }) {
    const userStore = useUserStore();

    let { proxy } = getCurrentInstance();

    let playing = ref(false);

    let kBps = ref(0);

    let { videoUrl, idx } = props;

    let fullscreen = ref(false);

    let uid = proxy._['uid']; //userStore.userInfo.id;

    watch(
      () => videoUrl,
      (e) => {
        nextTick(() => {
          console.log(e);
          onPlay(e);
        });
      },
      { immediate: true }
    );

    /**
     * 初始化视频插件
     */
    function onCreatedJessibuca() {
      let options = {
        container: proxy.$refs.container,
        autoWasm: true,
        background: '',
        controlAutoHide: false,
        debug: false,
        decoder: new URL(`@/assets/js/jessibuca/decoder.js`, import.meta.url).href,
        videoBuffer: 0.2, // 最大缓冲时长，单位秒
        isResize: true,
        forceNoOffscreen: false,
        heartTimeout: 5,
        heartTimeoutReplay: true,
        heartTimeoutReplayTimes: 3,
        hiddenAutoPause: false,
        hotKey: true,
        isFlv: false,
        isFullResize: false,
        keepScreenOn: true,
        loadingText: '请稍等, 视频加载中......',
        loadingTimeout: 10,
        loadingTimeoutReplay: true,
        loadingTimeoutReplayTimes: 3,
        openWebglAlignment: false,
        operateBtns: {
          fullscreen: false,
          screenshot: false,
          play: false,
          audio: false,
          record: false,
        },
        recordType: 'mp4',
        rotate: 0,
        showBandwidth: false,
        supportDblclickFullscreen: false,
        timeout: 10,
        useMSE: true,
        isNotMute: false,
        record: 'record',
        useWCS: location.hostname === 'localhost' || location.protocol === 'https:',
        useWebFullScreen: true,
        wasmDecodeErrorReplay: true,
        wcsUseVideoRender: true,
      };

      console.log(options);

      jessibucaPlayer[proxy._['uid']] = new window.Jessibuca(options);
      let jessibuca = jessibucaPlayer[proxy._['uid']];

      jessibuca.on('load', () => {
        console.log('on load init');
      });

      jessibuca.on('log', (msg) => {
        console.log('on log', msg);
      });

      jessibuca.on('pause', () => {
        playing.value = false;
      });
      jessibuca.on('play', () => {
        console.log('play....');
        playing.value = true;
      });
      jessibuca.on('fullscreen', (msg) => {
        fullscreen.value = msg;
      });
      jessibuca.on('kBps', (data) => {
        kBps.value = Math.round(data);
      });
    }

    /**
     * 播放视频
     */
    function handlePlayVideo() {
      onPlay(videoUrl);
    }

    /**
     * 播放视频
     */
    function onPlay(path) {
      console.log(proxy._['uid']);
      if (jessibucaPlayer[proxy._['uid']]) {
        // 销毁播放器
        handleDestroyJessibuca();
      }
      // 初始化播放器
      onCreatedJessibuca();
      jessibucaPlayer[proxy._['uid']].on('play', () => {
        playing.value = true;
      });
      if (jessibucaPlayer[proxy._['uid']].hasLoaded()) {
        jessibucaPlayer[proxy._['uid']].play(path);
      } else {
        jessibucaPlayer[proxy._['uid']].on('load', () => {
          jessibucaPlayer[proxy._['uid']].play(path);
        });
      }
    }

    /**
     * 销毁播放器
     */
    function handleDestroyJessibuca() {
      if (jessibucaPlayer[proxy._['uid']]) {
        jessibucaPlayer[proxy._['uid']].destroy();
      }
      jessibucaPlayer[proxy._['uid']] = null;
      playing.value = false;
      // emit('destroy');
    }

    /**
     * 暂停播放
     */
    function handlePauseVideo() {
      if (jessibucaPlayer[proxy._['uid']]) {
        jessibucaPlayer[proxy._['uid']].pause();
      }
      playing.value = false;
    }

    /**
     * 放大/缩小视频画面
     */
    function handleFullScreen() {
      let isFull = isFullscreen();
      jessibucaPlayer[proxy._['uid']].setFullscreen(!isFull);
      fullscreen.value = !isFull;
    }

    function isFullscreen() {
      return document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || false;
    }

    function updatePlayerDomSize() {
      nextTick(() => {
        let dom = proxy.$refs.container;
        let width = dom.parentNode.clientWidth;
        let height = (9 / 16) * width;

        const clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
        if (height > clientHeight) {
          height = clientHeight;
          width = (16 / 9) * height;
        }
        if (width > 0 && height > 0) {
          console.log(width + 'px');
          console.log(height + 'px');
          // dom.style.width = width + 'px';
          // dom.style.height = height + 'px';
        }
      });
    }

    onUnmounted(() => {
      if (Object.keys(jessibucaPlayer).length > 0) {
        Object.keys(jessibucaPlayer).forEach((k) => {
          jessibucaPlayer[k]?.destroy();
        });
      }
    });

    return {
      playing,
      fullscreen,
      kBps,
      onPlay,
      handlePlayVideo,
      handlePauseVideo,
      handleFullScreen,
      updatePlayerDomSize,
      handleDestroyJessibuca,
    };
  },
});
</script>

<style lang="less" scoped>
.player {
  position: relative;
  width: 100%;
  height: 100%;
  background: rgb(38, 38, 38);
  cursor: pointer;
  &:hover {
    color: #333;
    .btn-close {
      display: flex;
    }
  }
  .btn-close {
    position: absolute;
    top: 0;
    left: 0;
    display: none;
    width: 100%;
    padding: 0 12px;
    height: 35px;
    background: rgba(43, 51, 63, 0.7);
    z-index: 100;
    .anticon {
      cursor: pointer;
      font-size: 22px;
      color: #fff;
      &:hover {
        color: #333;
      }
    }
  }
  .btn-box {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 35px;
    background: rgba(43, 51, 63, 0.7);
    line-height: 35px;
    user-select: none;
    z-index: 100;
    .btn-box-left,
    .btn-box-right {
      .anticon {
        cursor: pointer;
        font-size: 22px;
        color: #fff;
      }
    }
    .btn-box-left {
      flex: 1;
      .anticon {
        margin: 0 12px;
        &:hover {
          color: #2a82e4;
        }
      }
    }
    .btn-box-right {
      flex: 1;
      color: #fff;
      .anticon {
        margin: 0 12px;
      }
    }
  }
}
</style>